home *** CD-ROM | disk | FTP | other *** search
- Path: news.th-darmstadt.de!news!enno
- From: enno@inferenzsysteme.informatik.th-darmstadt.de (Enno Sandner)
- Newsgroups: comp.lang.c++
- Subject: Re: External access to private class variables
- Date: 02 Feb 1996 19:34:23 GMT
- Organization: Fachbereich Informatik, TH Darmstadt
- Distribution: world
- Message-ID: <ENNO.96Feb2203423@kitz.inferenzsysteme.informatik.th-darmstadt.de>
- References: <4ermr9$ii7@cloner2.ix.netcom.com>
- NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
- In-reply-to: genescot@ix.netcom.com's message of 2 Feb 1996 00:45:29 GMT
-
- In article <4ermr9$ii7@cloner2.ix.netcom.com> genescot@ix.netcom.com(Eugene S. Thompson ) writes:
-
- I was playing around with references and ran across this situation. I'm
- sure it's not original, so I was hoping someone could tell me if it is
- an intentional implementation of C++ or if it is a bug.
-
- class X
- {
- private:
- int value;
- public:
- X (int n = 0) { value = n; }
- int& GSValue () { return value; } // return a reference to the
- // private member "value"
- };
- .
- .
- .
- main ()
- {
- X x1 (20);
-
- printf ("%d\n", x1.GSValue ()); // 20
-
- int* pntr = &(x1.GSValue ());
-
- printf ("%d\n", *pntr); // 20
-
- *pntr = 30;
- printf ("%d\n", x1.GSValue ()); // 30 -> We now have external
- // access to a private member.
- }
-
- I realize that this implementation is contrived, but I'm sure there are
- additional ways of gaining such access. So, what's the deal?
-
- It's even possible to modify the private member directly:
-
- int main ()
- {
- X x1 (20);
- printf ("%d\n", x1.GSValue ()); // 20
- x1.GSValue()=30;
- printf ("%d\n", x1.GSValue ()); // 30
- }
-
- You return a non-const reference and therefore it's perfectly valid to
- modify the referred variable. One should take care with services that
- provide uncontrolled access to private members.
-
- Enno
-